from django.db import models
from django.contrib.auth.models import User

class MedicineCategory(models.Model):
    name = models.CharField(max_length=100)
    description = models.TextField(blank=True)
    parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True)
    sort_order = models.IntegerField(default=0)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.name)

    class Meta:
        verbose_name_plural = "Medicine Categories"


class Medicine(models.Model):
    DATA_SOURCE_CHOICES = [
        ('manual', 'Manual'),
        ('api', 'API'),
        ('user', 'User'),
    ]

    barcode = models.CharField(max_length=100, unique=True)
    name = models.CharField(max_length=200)
    brand = models.CharField(max_length=200, blank=True)
    specification = models.CharField(max_length=200, blank=True)
    manufacturer = models.CharField(max_length=200, blank=True)
    category = models.ForeignKey(MedicineCategory, on_delete=models.SET_NULL, null=True, blank=True)
    usage = models.TextField(blank=True)
    precautions = models.TextField(blank=True)
    side_effects = models.TextField(blank=True)
    storage_conditions = models.TextField(blank=True)
    image_url = models.URLField(blank=True)
    data_source = models.CharField(max_length=10, choices=DATA_SOURCE_CHOICES, default='manual')
    verified = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    # 运营监控字段 - 对应首页药品相关统计
    view_count = models.IntegerField(default=0, help_text="药品查看次数")
    scan_success_count = models.IntegerField(default=0, help_text="扫码成功次数")
    last_viewed_at = models.DateTimeField(null=True, blank=True, help_text="最后查看时间")

    def __str__(self):
        return str(self.name)


class MyMedicine(models.Model):
    STATUS_CHOICES = [
        ('in_use', 'In Use'),
        ('paused', 'Paused'),
        ('used_up', 'Used Up'),
        ('discarded', 'Discarded'),
    ]

    family = models.ForeignKey('families.Family', on_delete=models.CASCADE)
    medicine = models.ForeignKey(Medicine, on_delete=models.CASCADE)
    added_by = models.ForeignKey(User, on_delete=models.CASCADE)
    quantity = models.IntegerField(default=1)
    location = models.CharField(max_length=100, default='家庭药箱')
    production_date = models.DateField()
    expiry_date = models.DateField()
    purchase_date = models.DateField(null=True, blank=True)
    purchase_price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
    purchase_location = models.CharField(max_length=200, blank=True)
    prescription_required = models.BooleanField(default=False)
    notes = models.TextField(blank=True)
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='in_use')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    
    # 运营监控字段 - 对应药品库存页状态管理
    last_inventory_check = models.DateTimeField(null=True, blank=True, help_text="最后库存检查时间")
    inventory_status = models.CharField(max_length=20, default='normal', help_text="库存状态(normal, low, overstock)")
    usage_frequency = models.IntegerField(default=0, help_text="使用频率统计")
    reminder_enabled = models.BooleanField(default=True, help_text="是否启用库存提醒")

    def __str__(self):
        return f"{self.medicine.name} - {self.family.name}"


class ScanRecord(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    family = models.ForeignKey('families.Family', on_delete=models.CASCADE)
    barcode = models.CharField(max_length=100)
    medicine = models.ForeignKey(Medicine, on_delete=models.CASCADE, null=True, blank=True)
    success = models.BooleanField()
    result_data = models.JSONField(null=True, blank=True)
    error_reason = models.CharField(max_length=200, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"Scan {self.barcode} by {self.user.username}"